<template>
  <view class="content">
    <view class="form">
      <view class="amount">
        <view class="symbol">￥</view>
        <input
          v-model="billData.amount"
          class="input"
          type="digit"
          placeholder="输入发生额"
          @focus="amountFocus"
        />
      </view>
      <view class="form-row">
        <view class="label">
          <image src="/static/icons/date.png" mode="aspectFit"></image>
          <view>日期</view>
        </view>
        
        <view class="value">
          <picker mode="date" :value="accDataValue"  @change="datePickerChange">
            <view>{{ accDateString }}</view>
          </picker>
        </view>
      </view>
      <view class="form-row">
        <view class="label">
          <image src="/static/icons/category.png" mode="aspectFit"></image>
          <view>分类</view>
        </view>
        <view class="value multi-box">
          <picker 
            class="picker"
            mode="multiSelector"
            :value='categoryData.value'
            :range="categoryData.range"
            @columnchange="categorySelectChange"
          >
            <view >
              <view type="text" placeholder="选择分类">{{ categoryString }}</view>
            </view>
          </picker>
          <view class="right" @click="toManageCategory">管理</view>
        </view>
      </view>
      <view class="form-row">
        <view class="label">
          <image src="/static/icons/name.png" mode="aspectFit"></image>
          <view>名称</view>
        </view>
        <view class="value">
          <input type="text" v-model="billData.name" placeholder="输入账单名称" />
        </view>
      </view>
      <view class="form-row">
        <view class="label">
          <image src="/static/icons/note.png" mode="aspectFit"></image>
          <view>备注</view>
        </view>
        <view class="value">
          <input type="text" v-model="billData.note" placeholder="输入备注" />
        </view>
      </view>
    </view>
    <view class="btn-action">
      <button
        class="save-btn"
        type="primary"
        :loading="billData.saveLoading"
        @click="saveStatement"
      >确认保存</button>
    </view>
    
    <view v-if="billData._id" class="del-action">
      <view
        class="del-btn"
        @click="deleteStatement"
      >删除记录</view>
    </view>
  </view>
</template>

<script setup>
  import { ref, reactive, computed } from 'vue';
  import { onLoad } from '@dcloudio/uni-app'
  import { dateFormat } from '@/utils/index'
  import { callCloudFunction } from '@/utils/cloudfunc.js'
  
  const accDate = ref(new Date())
  const accDataValue = ref(dateFormat(accDate.value, '-', true))  // 日期选择器的值
  const billData = reactive({
    _id: '',
    operateAction: 'createBill', // 默认为创建账单
    amount: 0.00,
    note: '',
    name: '',
    saveLoading: false,
  })
  
  const categoryData = reactive({
    value: [0, 0], // 显示的值索引
    range: [[''], ['']],
    ledger: []
  })
  
  const accDateString = computed(() => dateFormat(accDate.value, 'ch', false))
  const categoryString = computed(() => {
    let s = '';
    let col = 0;
    categoryData.value.forEach(i => {
      if (s.length > 0) s += ' - ';
      s += categoryData.range[col][i];
      col += 1;
    })
    return s
  })
  
  onLoad((options) => {
    // console.log(options);
    if (options.y) {
      accDate.value = new Date(options.y, options.m, options.d)
    }
    
    // 请求分类信息
    uni.showLoading({
      title:'数据加载中'
    })
    callCloudFunction({
      name: 'ume-ledger', data: {action: 'userRetrieve',}
    }).then(res => {
      uni.hideLoading()
      categoryData.ledger = res.ledger
      // 处理处第一级和当前子集的数据
      const firstLevel = getFirstLevelCategory()
      const firstLevelName = firstLevel.map(item => item.category_name)
      categoryData.range = [firstLevelName, []]
      if (firstLevelName.length > 1) {
        const ledgerId = getCategoryId(firstLevelName[0])
        if (!ledgerId) return
        categoryData.range[1] = getChildrenLedger(ledgerId).map(c => c.category_name)
      }
      
      // 放在分类返回的逻辑里，确保有分类数据
      if (options._id) {
        // 修改已有记录信息, 获取条目信息
        // console.log("options._id", options._id)
        billData._id = options._id
        getBillDetail()
      }
    })
  });
  
  // 取出第一级分类
  const getFirstLevelCategory = () => {
    const firstLevel = []
    categoryData.ledger.forEach(item => {
      if (!item.parent_id) {
        firstLevel.push(item)
      }
    })
    return firstLevel
  }
  
  // 取分类id下的子类信息
  const getChildrenLedger = (ledgerId) => {
    const children = []
    for (let i =0; i < categoryData.ledger.length; i++) {
      let item = categoryData.ledger[i]
      if (item.parent_id == ledgerId) {
        children.push(item)
      }
    }
    return children
  }
  
  // 查询指定账单数据
  const getBillDetail = () => {
    if (!billData._id) return
    callCloudFunction({
      name: 'ledger-bill',
      data: {action: 'getBill', bill_id: billData._id}
    }).then(res => {
      // console.log('查询账单返回:', res)
      const bill = res.bill
      billData._id = bill._id
      billData.amount = Number(bill.money / 100).toFixed(2)
      billData.name = bill.bill_name
      billData.note = bill.note
      // 设置日期显示
      accDate.value = new Date(bill.bill_time)
      accDataValue.value = dateFormat(accDate.value, '-', true)
      
      // 设置分类
      let ledgerDesc = undefined
      for (let i=0; i<categoryData.ledger.length; i++) {
        let item = categoryData.ledger[i]
        if (item._id == bill.ledger_id) {
          ledgerDesc = item
          break
        }
      }
      let parent = undefined
      for (let j=0; j<categoryData.ledger.length; j++) {
        let item = categoryData.ledger[j]
        if (item._id == ledgerDesc.parent_id) {
          parent = item
          break
        }
      }
      // console.log('desc:', ledgerDesc)
      // console.log('part:', parent)
      if (!ledgerDesc || !parent) return
      // 找到第一个所在的index
      const index1 = categoryData.range[0].indexOf(parent.category_name)
      categoryData.range[1] = getChildrenLedger(parent._id).map(c => c.category_name)
      const index2 = categoryData.range[1].indexOf(ledgerDesc.category_name)
      categoryData.value = [index1, index2]  // 设置显示名称
      
      // 设置操作方式
      billData.operateAction = 'updateBill'
    })
  }
  
  // 点击管理分类按钮
  const toManageCategory = () => {
    // uni.showModal({
    //   title: '开发中',
    //   content: '功能将尽快开放，敬请期待！'
    // })
    uni.navigateTo({
      url: '/pages/account/category/index'
    })
  }
  
  // 金额输入框聚焦
  const amountFocus = () => {
    if (billData.amount == 0) {
      billData.amount = ''
    }
  }
  
  // 找到分类的id
  const getCategoryId = (name) => {
    let ledgerId = ''
    for (let i =0; i < categoryData.ledger.length; i++) {
      let item = categoryData.ledger[i]
      if (item.category_name == name) {
        ledgerId = item._id
        break
      }
    }
    return ledgerId
  }
  
  
  // 选择器发生改变
  const categorySelectChange = (e) => {
    const {column, value} = e.detail;  // [列索引，值索引]
    if (column == 0) {
      const colName = categoryData.range[column][value]
      const ledgerId = getCategoryId(colName)
      // console.log(colName, ledgerId);
      if (!ledgerId) return
      categoryData.range[1] = getChildrenLedger(ledgerId).map(c => c.category_name)
      categoryData.value[1] = 0
    }
    categoryData.value[column] = value; // 设置显示的数据
  }
  
  // 日期选择改变
  const datePickerChange = (e) => {
    const value = e.detail.value
    accDate.value = new Date(value)
  }
  
  // 验证账单数据
  const validateBill = (data) => {
    if (!data.money) return '请填写账单金额'
    if (!data.bill_time) return '请选择账单日期'
    if (!data.ledger_id) return '请选择账单分类'
    if (!data.bill_name) return '请输入账务名称'
    return true
  }
  
  // 保存账单
  const saveStatement = () => {
    
    const ledgerName = categoryData.range[1][categoryData.value[1]]
    const statement = {
      _id: billData._id,
      money: parseInt((billData.amount * 100).toFixed(0)),
      bill_time: accDate.value.getTime(),
      ledger_id: getCategoryId(ledgerName),
      bill_name: billData.name,
      note: billData.note
    }
    // 验证数据
    const validateRes = validateBill(statement)
    if (validateRes !== true) {
      uni.showModal({
        title:'错误',
        content: validateRes
      })
      return
    }
    
    
    uni.showLoading({
      title: '正在操作'
    })
    billData.saveLoading = true
    callCloudFunction({
      name: 'ledger-bill',
      data: {action: billData.operateAction, 'bill_data': statement}
    }).then(res => {
      // 保存账单返回
      // console.log('账单操作返回:', res);
      uni.hideLoading()
      billData.saveLoading = false
      uni.showModal({
        title: '结果',
        content: res.message,
        showCancel:true,
        cancelText: '返回',
        success: (res) => {
          if (res.confirm) {
            if (res._id) {
              billData.amount = ''
            }
            if (billData.operateAction == 'updateBill') {
              uni.navigateBack()
            }
          } else if (res.cancel) {
            uni.navigateBack()
          }
        }
      })
    }).catch(err => {
      uni.hideLoading()
      billData.saveLoading = false
      uni.showModal({
        title:'错误',
        content:err
      })
    })
  }
  
  // 删除账单
  const deleteStatement = () => {
    uni.showModal({
    	title: '警告',
    	content: '确定删除该记录吗，操作不可恢复!',
    	success: (res) => {
    		if (res.confirm) {
          delBillRecord()
    		} else if (res.cancel) {
    		}
    	}
    });
  }
  
  const delBillRecord = (billId) => {
    callCloudFunction({
      name: 'ledger-bill',
      data: {action: 'delBill', _id: billData._id}
    }).then(res => {
      uni.showModal({
        title: '结果',
        content: res.message,
        showCancel:false,
        success: () => {
          uni.navigateBack()
        }
      })
    })
  }
</script>

<style lang="scss">
  .content {
    .form {
      padding: 20rpx;
      .amount {
        padding-left: 50rpx;
        display: flex;
        align-items: center;
        color: #3c7a03;
        font-weight: 700;
        .symbol {
          font-size: 32rpx;
          margin-right: 10rpx;
        }
        .input {
          font-size: 50rpx;
          height: 100rpx;
        }
      }
      .form-row {
        display: flex;
        flex-direction: row;
        align-items: center;
        line-height: 70rpx;
        margin-bottom: 20rpx;
        border-bottom: 1px solid #eee;
        .label {
          width: 160rpx;
          display: flex;
          align-items: center;
          flex-direction: row;
          color: #555;
          font-weight: 700;
          font-size: 28rpx;
          image {
            width: 50rpx;
            height: 50rpx;
            margin-right: 10rpx;
          }
        }
        .value {
          width: 100%;
          height: 60rpx;
          margin-left: 20rpx;
          input {
            height: 60rpx;
          }
        }
        .multi-box {
            display: flex;
            .picker {
              flex: 1;
            }
            .right {
              margin-left: auto;
              color: #3c7a03;
              font-size: 28rpx;
            }
          }
      }
    }
    .btn-action {
      display: flex;
      justify-content: center;
      align-items: center;
      margin-top: 50rpx;
      .save-btn {
        width: 50%;
      }
    }
  .del-action {
    display: flex;
    justify-content: center;
    align-items: center;
    .del-btn {
      margin-top: 50rpx;
      color: #ff6433;
    }
  }
  }
</style>